package cz.zcu.fav.rat.managed.validator;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import cz.zcu.fav.rat.beans.User;
import cz.zcu.fav.rat.dataaccess.service.UserService;
import cz.zcu.fav.rat.managed.bean.SpringBeanFactory;
import cz.zcu.fav.rat.managed.locale.LocaleMessageFactory;

@FacesValidator(value = "userValidator")
public class UserValidator implements Validator
{
	private Pattern pattern;

	private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
			+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

	public UserValidator()
	{
		pattern = Pattern.compile(EMAIL_PATTERN);
	}

	@Override
	public void validate(FacesContext arg0, UIComponent component, Object arg2)
			throws ValidatorException
	{
		UIInput emailInput = (UIInput) component.getAttributes().get("email");

		UIInput usernameInput = (UIInput) component.getAttributes()
				.get("username");

		Integer id = (Integer) component.getAttributes().get("usrid");

		String email = (String) emailInput.getSubmittedValue();
		String username = (String) usernameInput.getSubmittedValue();

		Matcher matcher = pattern.matcher(email);
		if (!matcher.matches())
		{
			String message = LocaleMessageFactory
					.getLocale("view.usercreate.error.invalidemail");

			emailInput.setValid(false);
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
					message, null);

			throw new ValidatorException(msg);
		}

		UserService service = SpringBeanFactory.getInstance().getBean(
				"userService", UserService.class);
		List<User> users = service.findByNickname(username);
		if (users.isEmpty())
		{
			return;
		}
		User user = users.iterator().next();
		if (id != null && user.getId().equals(id))
		{
			return;
		}
		usernameInput.setValid(false);
		throwDuplicateUsernameEx();

	}

	private void throwDuplicateUsernameEx() throws ValidatorException
	{
		String message = LocaleMessageFactory
				.getLocale("view.usercreate.error.duplicitnickname");

		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
				message, null);

		throw new ValidatorException(msg);

	}
}
